package com.linghang.demo.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.linghang.demo.domain.Joinus;
import com.linghang.demo.domain.JoinusExample;
import com.linghang.demo.mapper.JoinusMapper;
import com.linghang.demo.req.JoinusQueryReq;
import com.linghang.demo.req.JoinusSaveReq;
import com.linghang.demo.resp.JoinusQueryResp;
import com.linghang.demo.resp.PageResp;
import com.linghang.demo.util.CopyUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Service
public class JoinusService {
    private int id=10;
    @Resource
    private JoinusMapper joinusMapper;
    private static final Logger LOG = LoggerFactory.getLogger(JoinusService.class);

    public List<Joinus> list(){
        return joinusMapper.selectByExample(null);
    }

    public PageResp<JoinusQueryResp> list(JoinusQueryReq req) {
        JoinusExample joinusExample = new JoinusExample();
        JoinusExample.Criteria criteria = joinusExample.createCriteria();
        if (!ObjectUtils.isEmpty(req.getId())) {
            criteria.andIdEqualTo(  req.getId() );
        }

        PageHelper.startPage(req.getPage(), req.getSize());
        List<Joinus> joinusList = joinusMapper.selectByExample(joinusExample);

        PageInfo<Joinus> pageInfo = new PageInfo<>(joinusList);
        LOG.info("总行数：{}", pageInfo.getTotal());
        LOG.info("总页数：{}", pageInfo.getPages());

        // List<JoinusResp> respList = new ArrayList<>();
        // for (Joinus joinus : joinusList) {
        //     // JoinusResp joinusResp = new JoinusResp();
        //     // BeanUtils.copyProperties(joinus, joinusResp);
        //     // 对象复制
        //     JoinusResp joinusResp = CopyUtil.copy(joinus, JoinusResp.class);
        //
        //     respList.add(joinusResp);
        // }

        // 列表复制
        List<JoinusQueryResp> list = CopyUtil.copyList(joinusList, JoinusQueryResp.class);

        PageResp<JoinusQueryResp> pageResp = new PageResp();
        pageResp.setTotal(pageInfo.getTotal());
        pageResp.setList(list);

        return pageResp;
    }

    /**
     * 保存
     */
    public void save(JoinusSaveReq req) {
        Joinus joinus= CopyUtil.copy(req, Joinus.class);
        if (ObjectUtils.isEmpty(req.getId())) {
            // 新增
            joinus.setId(id++);
            joinusMapper.insert(joinus);

        } else {
            // 更新
            joinusMapper.updateByPrimaryKey(joinus);

        }
    }

    
    public void  delete(int id){
        joinusMapper.deleteByPrimaryKey(id);
    }
}
